package gui;


import java.util.List;

import javax.swing.ListCellRenderer;

import org.jdesktop.swingx.JXList;

import sys.DownloadProgressListener;
import sys.Video;
import sys.Video.Status;
import sys.VideoListModel;

public class VideoList extends JXList implements DownloadProgressListener {
	ListCellRenderer renderer;
	TotalSpeedCalculator totalSpeedCalculator;
	public VideoList() {
		super();
		this.setModel(new VideoListModel());
		renderer = new VideoCellRenderer();
		this.setCellRenderer(renderer);
		totalSpeedCalculator = new TotalSpeedCalculator();
		totalSpeedCalculator.start();
		
		final Video test = new Video("test", "a", "b");
		final Video test2 = new Video("test2", "a", "b");
		final Video test3 = new Video("test3", "a", "b");
		test.setStatus(Status.DOWNLOADING);
		test2.setStatus(Status.DOWNLOADING);
		test3.setStatus(Status.DONE);
		((VideoListModel)this.getModel()).addVideo(test);
		((VideoListModel)this.getModel()).addVideo(test2);
		((VideoListModel)this.getModel()).addVideo(test3);
		new Thread() {
			int i = 0;
			public void run() {
				while(true) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					test.setDownloadProgress(i);
					test.addSpeed((double)i);
					i += (i < 100) ? 1 : -i;
				}
			}
		}.start();
		new Thread() {
			int i = 0;
			public void run() {
				while(true) {
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					test2.setDownloadProgress(i);
					test2.addSpeed((double)i);
					i += (i < 100) ? 1 : -i;
				}
			}
		}.start();
	}
	
	@Override
	public void updateDownloadProgress(Video video) {
		
	}
	
	public void addVideos(List<Video> videos) {
		for(Video v : videos) {
			((VideoListModel)this.getModel()).addVideos(videos);
		}
	}
	
	public String getTotalSpeed() {
		double s = 0;
		for(Video v : ((VideoListModel)this.getModel()).getVideos()) {
			//TODO change to actual speed readings...
			s += v.getDownloadProgress();
		}
		return ""+s;
	}
	
	class TotalSpeedCalculator extends Thread {

		@Override
		public void run() {
			while(true) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				GVOD.setTotalSpeedString(getTotalSpeed());
			}
		}
		
	}
	
}